<template>
  <div class="sidebar-container">
    <el-menu
      :default-active="activeMenu"
      class="el-menu-vertical-demo"
      background-color="#0f172a"
      text-color="#94a3b8"
      active-text-color="#fff"
      @select="handleMenuSelect"
      :collapse="isSidebarCollapse"
      :collapse-transition="false"
    >
      <template v-for="menu in menus" :key="menu.path">
        <!-- 有子菜单的情况 -->
        <el-sub-menu v-if="menu.children && menu.children.length" :index="menu.path">
          <template #title>
            <el-icon :size="18"><component :is="menu.meta.icon" /></el-icon>
            <span v-if="!isSidebarCollapse">{{ menu.meta.title }}</span>
          </template>
          <template v-for="subMenu in menu.children" :key="subMenu.path">
            <el-menu-item :index="subMenu.path">
              <el-icon :size="18"><component :is="subMenu.meta.icon" /></el-icon>
              <span v-if="!isSidebarCollapse">{{ subMenu.meta.title }}</span>
            </el-menu-item>
          </template>
        </el-sub-menu>
        
        <!-- 无子菜单的情况 -->
        <el-menu-item v-else :index="menu.path">
          <el-icon :size="18"><component :is="menu.meta.icon" /></el-icon>
          <span v-if="!isSidebarCollapse">{{ menu.meta.title }}</span>
        </el-menu-item>
      </template>
    </el-menu>
  </div>
</template>

<script setup>
import { useMenuStore } from '@/store'
import { useTabsStore } from '@/store'
import { useRouter } from 'vue-router'
import {Platform, Setting, User } from '@element-plus/icons-vue'
import { inject } from 'vue'

const menuStore = useMenuStore()
const tabsStore = useTabsStore()
const router = useRouter()

// 接收从父组件传入的侧边栏伸缩状态
const isSidebarCollapse = inject('isSidebarCollapse')

const { menus, activeMenu } = menuStore

// 处理菜单选择
const handleMenuSelect = (path) => {
  // 更新当前激活的菜单
  menuStore.setActiveMenu(path)
  
  // 找到对应的路由信息
  const route = findRouteByPath(router.getRoutes(), path)
  
  if (route) {
    // 添加到标签页
    tabsStore.addTab({
      path: route.path,
      name: route.name,
      title: route.meta.title
    })
    
    // 导航到对应的路由
    router.push(path)
  }
}

// 根据路径查找路由
const findRouteByPath = (routes, path) => {
  for (const route of routes) {
    if (route.path === path) {
      return route
    }
    if (route.children && route.children.length) {
      const found = findRouteByPath(route.children, path)
      if (found) return found
    }
  }
  return null
}
</script>

<style scoped lang="scss">
.sidebar-container {
  height: 100%;
  padding-top: 20px;
}

.el-menu-vertical-demo:not(.el-menu--collapse) {
  width: 200px;
  min-height: 400px;
}

// 收缩状态下的样式调整
:deep(.el-menu--collapse) {
  width: 60px;
  
  .el-submenu__title span,
  .el-menu-item span {
    display: none;
  }
  
  .el-submenu__icon-arrow {
    display: none;
  }
}
</style>